from concurrent.futures import ThreadPoolExecutor, as_completed
import time

def process_task(task_id):
    """模拟任务处理函数"""
    print(f"开始处理任务 {task_id}")
    time.sleep(1)  # 模拟任务执行时间
    return f"任务 {task_id} 已完成"

# 固定任务的处理
def fixed_task():
    total_tasks = 20
    thread_pool_size = 2
    
    # 创建线程池
    with ThreadPoolExecutor(max_workers=thread_pool_size) as executor:
        futures = []
        next_task_id = 0
        
        # 初始提交所有任务
        for i in range(total_tasks):
            future = executor.submit(process_task, i)
            futures.append(future)
        
        # 等待所有任务完成并处理结果
        for future in as_completed(futures):
            try:
                result = future.result()
                print(result)
            except Exception as e:
                print(f"任务出错: {e}")

    print("所有任务已完成")


# 动态添加任务
def dynamic_task():
    total_tasks = 20
    thread_pool_size = 2
    
    # 创建线程池
    with ThreadPoolExecutor(max_workers=thread_pool_size) as executor:
        futures = set()
        next_task_id = 0
        
        # 初始提交第一批任务
        while next_task_id < thread_pool_size and next_task_id < total_tasks:
            future = executor.submit(process_task, next_task_id)
            futures.add(future)
            next_task_id += 1
        
        # 动态监测并添加新任务
        while futures:
            # 等待至少一个任务完成
            done, _ = as_completed(futures), None
            for future in done:
                futures.remove(future)
                try:
                    result = future.result()
                    print(result)
                except Exception as e:
                    print(f"任务出错: {e}")
                
                # 添加新任务
                if next_task_id < total_tasks:
                    new_future = executor.submit(process_task, next_task_id)
                    futures.add(new_future)
                    next_task_id += 1



if __name__ == "__main__":
    dynamic_task()